#!/usr/bin/python

# Flag para teste unitario
flag_unit_test=0
#flag_unit_test=1

# teste unitario
if flag_unit_test==1:
	import sys
	sys.path.append("lib/log")
 
import os
import MySQLdb
from log import Log
c=0

class Dados:

	def __init__(self):

		self.log = Log()
		self.log.update('Dados iniciada...\n')
		self.log.update('###################\n')
		# Open file configuration
		str_file = open('/tmp/db.cfg', 'r').read()
		conexao=str_file.split('\n')
		self.servidor=conexao[0].split('=')[1]
		self.usuario=conexao[1].split('=')[1]
		self.senha=conexao[2].split('=')[1]
		self.database=conexao[3].split('=')[1]
			
		# Open database connection
		#self.db = MySQLdb.connect(self.servidor, self.usuario, self.senha, self.database )
		self.query=""
		#self.executeQuery()

	def executeQuery(self):

		self.openDados()
		#global c
		#c=c+1
		#self.log.update('c: ' + str(c) + '\n')
		
		# prepare a cursor object using cursor() method
		cursor = self.db.cursor()

		try:
			#self.log.update('Executando Query: ' + self.query + ":" + str(self.data) + '\n')
			#self.log.update('Executando Query: ' + self.query + '\n')
			# execute SQL query using execute() method.
			cursor.execute(self.query)
			#self.log.update("%d row(s) were updated\n" % cursor.rowcount)

			# Fetch a single row using fetchone() method.
			self.data = cursor.fetchall()
			cursor.close()
			self.db.commit()

		except MySQLdb.Error, e:
			self.log.update('Fail getting query [' + self.query + ']:')
     			self.log.update("Error %d: %s\n" % (e.args[0], e.args[1]))
			self.db.rollback()

		self.closeDados()

	def openDados(self):
		# connect to server
		self.db = MySQLdb.connect(self.servidor, self.usuario, self.senha, self.database )

	def closeDados(self):
		# disconnect from server
		self.db.close()

	def getDados(self):

		return self.data

	def setQuery(self,s):

		self.query=s

	
	def getEntradas(self):

		self.query="SELECT * FROM v_getPathEntrada;"
		self.executeQuery()
		return self.data


	def getSaidas(self):

		self.query="SELECT * FROM getSaidas;"
		self.executeQuery()
		return self.data


	def getProcessamento(self):

		self.query="SELECT * FROM getProcessamento;"
		#self.closeDados()
		#self.openDados()
		#self.data=[]
		self.executeQuery()
		return self.data

	def getExecutor(self,i):

		self.query="SELECT * FROM executor where id_sistema=" + str(i) +";"
		self.executeQuery()
		return self.data[0]

	def getParametros(self,i):

		self.query="SELECT * FROM parametros_entrada where id_sistema=" + str(i) +" and id_processamento=0;"
		self.executeQuery()
		return self.data

	def setParametrosProcessamento(self,s,p):
		self.query="update parametros_entrada set id_processamento=" + str(p) + " where id_sistema=" + str(s) +" and id_processamento=0;"
		self.executeQuery()

	def getParametrosEntrada(self,s,p):

		self.query="SELECT parametros FROM parametros_entrada where id_sistema=" + str(s) +" and id_processamento=" + str(p) + ";"
		self.executeQuery()
		#print "RAS - Parametros Entrada:"
		if len(self.data) == 0:
			return ""
		else:
			return self.data[0][0]

	def getTarefas(self,i):

		self.query="SELECT * FROM tarefa where id_executor=" + str(i) +";"
		self.executeQuery()
		return self.data

	def lockProcessamento(self,i):

		#self.query="lock tables processamento write;"
		#self.executeQuery()
		self.query="select lockProcessamento(" + str(i) +");"
		self.executeQuery()
		data=self.data[0][0]
		#self.query="unlock tables;"
		#self.executeQuery()
		return data

	def unlockEntradaProcessamento(self,i):

		self.query="select id_projeto from processamento where id_processamento=(" + str(i) +");"
		self.executeQuery()
		data=self.data
		self.query="select unlockEntrada(" + str(data[0][0]) +");"
		self.executeQuery()
		data=self.data
		return data

	def lockEntrada(self,i):

		self.query="select lockEntrada(" + str(i) +");"
		self.executeQuery()
		data=self.data[0][0]
		return data

	def unlockEntrada(self,i):

		self.query="select unlockEntrada(" + str(i) +");"
		self.executeQuery()
		data=self.data
		return data

	def lockSaida(self,i):

		self.query="select lockSaida(" + str(i) +");"
		self.executeQuery()
		data=self.data
		return data

	def unlockSaida(self,i):

		self.query="select unlockSaida(" + str(i) +");"
		self.executeQuery()
		data=self.data
		return data

	def setProcessamentoStatus(self, iproc, isis, s):

		self.query="update processamento set status=" + str(s) + " where id_processamento=" + str(iproc) +" and id_sistema=" + str(isis) + ";"
		#self.closeDados()
		#self.openDados()
		self.executeQuery()

	def setExecutorStatus(self,i,s):

		self.query="update executor set status=" + str(s) + " where id_executor=" + str(i) +";"
		#self.closeDados()
		#self.openDados()
		self.executeQuery()


	def getProcessamentoStatus(self,i):

		self.query="SELECT status FROM processamento where id_processamento = " + str(i) + ";"
		#self.closeDados()
		#self.openDados()
		#self.data=[]
		self.executeQuery()
		return self.data

	def getProcessamentosFinalizados(self,i):

		self.query="SELECT id_processamento FROM processamento where id_sistema = " + str(i) + " and status=3;"
		#self.closeDados()
		#self.openDados()
		#self.data=[]
		self.executeQuery()
		if len(self.data) == 0:
			return 0 
		else:
			return self.data

	def getStatusIO(self, p, i):

		self.query="SELECT status FROM v_getIO where id_processamento=" + str(p) + " and tipo_io=" + str(i) + ";"
		self.executeQuery()
		print "TESTE="
		print self.data
		return self.data[0][0]

	def setIO(self, p, i, s):

		self.query="call setIO(" + str(p) + " ," + str(i) + ", " + str(s) + ");"
		self.executeQuery()
#teste local
if flag_unit_test==1:
	teste = Dados()
	#a=teste.getEntradas()
	#print a
	#print a[0][2]
	#a=teste.getProcessamento()
	#print a
	query="update tarefa set status=2 where id_tarefa=1"
	teste.setQuery(query)
	teste.executeQuery()
	#print a
	
